<template>
  <div class="wrapper">
    <div class="board">
      <ul class="board__ul">
        <li
          v-for="(item, index) in receiveInfo"
          :key="index"
          :class="item.id != user ? 'board__li' : 'board__limi'"
        >
          <img src="@assets/user.png" alt="" class="board__li__icon" v-show="item.id != user" />
          <div class="" :class="item.id != user ? 'board__li__message' : 'board__limi__messagemi'">
            {{ item.message }}
          </div>
          <img src="@assets/user.png" alt="" class="board__limi__iconmi" v-show="item.id == user" />
        </li>
      </ul>
    </div>
    <van-field v-model="chat" placeholder="请输入用户名" class="chart__border">
      <van-button type="primary" slot="button" size="small" @click="publish">publish</van-button>
    </van-field>
  </div>
</template>
<script>
  import { mapGetters } from 'vuex';
  export default {
    computed: mapGetters({ location: 'generator/location' }),
    data() {
      return {
        address: '',
        client: '',
        chat: '',
        user: '',
        wsurl: 'ws://49.233.85.23:8080/study/websocket/sniper/',
        lockReconnect: false,
        heartCheck: '',
        receiveInfo: [],
        usersList: []
      };
    },
    methods: {
      websocketCheck() {
        var _this = this;
        if ('WebSocket' in window) {
          console.log('您的浏览器支持 WebSocket!');
          if (_this.client) {
            _this.client.close();
            _this.client = '';
          }
          // 打开一个 web socket
          _this.user = Math.random() * 10000;
          _this.user = Math.round(_this.user);
          //_this.client = new WebSocket('ws://'+window.location.host+'/study/websocket/sniper/' + _this.user);
          _this.client = new WebSocket(
            'ws://49.233.85.23:8080/study/websocket/sniper/' + _this.user
          );
          _this.client.onopen = function() {
            console.log(_this.client, 'websocket连接上了');
          };
          _this.client.onmessage = function(evt) {
            console.log('-------------数据已接收...', evt);
            console.log(evt.data);
            _this.receiveInfo.push(JSON.parse(evt.data));
          };
          _this.client.onclose = function() {
            // 关闭 websocket
            _this.reconnect();
            console.log('连接已关闭...');
          };
          _this.client.onerror = function() {
            _this.reconnect();
          };
        } else {
          // 浏览器不支持 WebSocket
          alert('您的浏览器不支持 WebSocket!');
        }
      },
      reconnect() {
        var _this = this;
        if (_this.lockReconnect) return;
        _this.lockReconnect = true;
        //没连接上会一直重连，设置延迟避免请求过多
        setTimeout(function() {
          console.info('尝试重连...');
          _this.websocketCheck();
          _this.lockReconnect = false;
        }, 1000);
      },
      heartBeat() {
          var _this = this;
        _this.heartCheck = {
          timeout: 5000,
          timeoutObj: null,
          serverTimeoutObj: null,
          reset: function() {
            clearTimeout(this.timeoutObj);
            clearTimeout(this.serverTimeoutObj);
            return this;
          },
          start: function() {
            var self = this;
            this.timeoutObj = setTimeout(function() {
              //这里发送一个心跳，后端收到后，返回一个心跳消息，
              //onmessage拿到返回的心跳就说明连接正常
              _this.client.send('HeartBeat' + new Date().format('yyyy-MM-dd hh:mm:ss'));
              console.info('客户端发送心跳：' + new Date().format('yyyy-MM-dd hh:mm:ss'));
              self.serverTimeoutObj = setTimeout(function() {
                //如果超过一定时间还没重置，说明后端主动断开了

                _this.client.close(); //如果onclose会执行reconnect，我们执行ws.close()就行了. //如果直接执行reconnect 会触发onclose导致重连两次
              }, self.timeout);
            }, this.timeout);
          }
        };
      },
      publish() {
        var _this = this;
        console.log('数据发送中...');
        _this.client.send(_this.chat);
        _this.chat = '';
      },
      closeWs() {
        var _this = this;
        console.log('关闭websocket...');
        _this.client.close();
      },
      onClickLeft() {
        var _this = this;
        console.log(_this, '8888888');
        _this.client.close();
        window.$utils.exit();
      },
      onClickRight() {
        var _this = this;
        _this.$toast(99);
      }
    },
    created(){
      console.log('creating');
      var _this = this;
      if(_this.client){
        _this.client.close();
        _this.client='';
      }
    },
    mounted() {
      var _this = this;
      //console.log(_this.serializeToUrl('woshinima'), '----', window);
      _this.websocketCheck();
      document.addEventListener('keyup', function(e) {
        if (e.key == 'Enter') {
          _this.publish();
        }
      });
    },
    destroyed(){
      var _this = this;
      console.log('destroyed..........');
      _this.client.close();
      _this.client='';
    }
  };
</script>
<style scoped lang="less">
  .wrapper {
  }
  .board {
    width: 100%;
    height: calc(100% - 52px);
    background-color: @regular-background;
    &__ul {
      height: calc(100% - 40px);
      overflow: scroll;
      padding: 20px;
    }
    &__li {
      width: 100%;
      min-height: 30px;
      display: flex;
      flex-flow: row;
      margin-bottom: 10px;
      position:relative;
      &__icon {
        width: 30px;
        height: 30px;
        margin-right: 10px;
      }
      &__message {
        max-width: calc(100% - 30px);
        min-height: 30px;
        text-align: left;
        overflow: auto;
        word-break: break-all;
        line-height: 30px;
        padding: 0 10px;
        background-color: @white;
        border-radius: 5px;
        box-shadow: @regular-box-shadow;
      }
      &__message :before{
        content:'';
        position:absolute;
        left:0;
        width:0;
        height:0;
        border-top:20px solid transparent;
        border-bottom:20px solid transparent;
        border-left: 20px solid white;
      }
    }
    &__li__message:before{
      content:'';
      position:absolute;
      left:30px;
      top:10px;
        width:0;
        height:0;
        border-top:5px solid transparent;
        border-bottom:5px solid transparent;
        border-right: 10px solid @white;
    }
    &__li__messagemi:before{
      content:'';
      position:absolute;
      right:30px;
      top:10px;
        width:0;
        height:0;
        border-top:5px solid transparent;
        border-bottom:5px solid transparent;
        border-right: 10px solid yellowgreen;
    }
    // &__li ::before {
    //   content: '';
    //   width: 10px;
    //   position: absolute;
    //   height: 0;
    //   border-left: 1px;
    // }
    &__limi {
      width: 100%;
      min-height: 30px;
      display: flex;
      flex-flow: row;
      justify-content: flex-end;
      margin-bottom: 10px;
      &__iconmi {
        width: 30px;
        height: 30px;
        margin-left: 10px;
      }
      &__messagemi {
        max-width: calc(100% - 40px);
        min-height: 30px;
        text-align: right;
        line-height: 30px;
        overflow: auto;
        word-break: break-all;
        padding: 0 10px;
        background-color: yellowgreen;
        border-radius: 5px;
        box-shadow: @regular-box-shadow;
      }
    }
  }
  .chart {
    &__border {
      border: 1px solid @regular-border-color;
    }
  }
</style>
